Skip to main content

Static Variables

By using a static variable we can retain a value across the entire program. To create a static variable in JavaScript, add an instance property to the function.

// console.log(x);
function sum(x, y) {
sum.totalSum = sum.totalSum + x + y; // calculate current sum
return sum.totalSum; // return current sum
}
// Define a static variable to hold the value from the function sum
sum.totalSum = 0;
var x = sum(2, 3);
console.log(x);
var x = sum(5, 3);
console.log(x);
Note

If you need to keep values from one invocation to another, static variables should be used as global variable.